package com.gimi.cloud.bbp.manage.service.sys.impl;

import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.dao.dao.sys.SysAuthorityDao;
import com.gimi.cloud.bbp.dto.sys.SysAuthorityDTO;
import com.gimi.cloud.bbp.entity.sys.SysAuthorityEntity;
import com.gimi.cloud.bbp.manage.service.sys.SysAuthorityService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 权限集合相关接口实现类
 *
 * @author wbj
 * @version 1.0
 * @Description
 * @create 2018-01-25
 **/
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
public class SysAuthorityServiceImpl implements SysAuthorityService {
    private static final Logger logger = LoggerFactory.getLogger(SysAuthorityServiceImpl.class);
    private SysAuthorityDao sysAuthorityDao;

    @Autowired
    public SysAuthorityServiceImpl(SysAuthorityDao sysAuthorityDao) {
        this.sysAuthorityDao = sysAuthorityDao;
    }

    @Override
    public SysAuthorityDTO doAuth(SysAuthorityDTO dto, Integer roId, String meIds) throws Exception {
        if(null == roId){
            throw new MsgException(ResponseCodeEnum.MANAGE_AUTH_DO_AUTH_ERR,"角色Id为空，授权失败");
        }
        //根据角色id删除所有的授权
        sysAuthorityDao.deleteByRoleId(roId);
        //根据菜单id生成授权数据
        if(StringUtils.isNotBlank(meIds)){
            List<SysAuthorityEntity> authoritys = new ArrayList<>();
            SysAuthorityEntity authority = null;
            for(String meId:meIds.split(",")){
                if(StringUtils.isNotBlank(meId)){
                    authority = new SysAuthorityEntity();
                    authority.setRoId(roId);
                    authority.setMeId(Integer.valueOf(meId));
                    authority.setAuCreated(new Date());
                    authoritys.add(authority);
                }
            }
            sysAuthorityDao.insertList(authoritys);
        }
        return dto;
    }
}
